package com.shoothzj.example.storage.mongo;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.shoothzj.example.storage.core.AbstractDbService;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;

public class MongoGenericService<T> extends AbstractDbService<T> {
    protected final MongoClient mongoClient;

    protected final MongoCollection<Document> collection;

    protected MongoGenericService(Class<T> tClass, MongoGenericContext genericContext) {
        super(tClass);
        this.mongoClient = genericContext.getMongoClient();
        this.collection = mongoClient.getDatabase(this.tableName).getCollection(tableName);
    }

    @Override
    public List<T> findAll() {
        List<T> result = new ArrayList<>();
        final FindIterable<Document> documents = collection.find();
        for (Document document : documents) {
            result.add(document2Generic(document));
        }
        return result;
    }

    @Override
    public long count() {
        return collection.countDocuments();
    }

    protected T document2Generic(Document document) {
        final T newInstance;
        try {
            newInstance = tClass.newInstance();
            // todo document to generic
        } catch (Exception e) {
            throw new IllegalStateException("document2Generic error", e);
        }
        return newInstance;
    }

    protected Document generic2Document(T t) {
        final Document document = new Document();
        return document;
    }
}
